<template>
  <div class="shop-rent-payment" v-loading="loading">
    <!-- 租金信息 -->
    <el-card shadow="never" class="rent-info-card">
      <template #header>
        <div class="card-header">
          <el-icon><Money /></el-icon>
          <span>租金信息</span>
        </div>
      </template>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="店铺名称">
          <el-tag type="primary" size="large">{{ rentInfo.shopName || '未知店铺' }}</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="业主姓名">
          <span class="name-text">{{ rentInfo.ownerName || '未知业主' }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="租金金额">
          <span class="money-text">¥{{ formatMoney(rentInfo.rentAmount) }}</span>
        </el-descriptions-item>
        <el-descriptions-item label="租金期间">
          {{ rentInfo.rentPeriod || '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="租金开始日期">
          {{ rentInfo.rentStartDate || '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="租金结束日期">
          {{ rentInfo.rentEndDate || '未知' }}
        </el-descriptions-item>
        <el-descriptions-item label="支付状态">
          <el-tag :type="getPaymentStatusTagType(rentInfo.paymentStatus)">
            {{ getPaymentStatusName(rentInfo.paymentStatus) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="到期日期">
          {{ rentInfo.dueDate || rentInfo.rentEndDate || '未知' }}
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 支付表单 -->
    <el-form
      ref="formRef"
      :model="paymentForm"
      :rules="formRules"
      label-width="120px"
      size="default"
      class="payment-form"
    >
      <el-form-item label="支付方式" prop="paymentMethod">
        <el-radio-group v-model="paymentForm.paymentMethod">
          <el-radio value="CASH">现金</el-radio>
          <el-radio value="BANK_TRANSFER">银行转账</el-radio>
          <el-radio value="ALIPAY">支付宝</el-radio>
          <el-radio value="WECHAT">微信支付</el-radio>
          <el-radio value="OTHER">其他</el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item label="支付日期" prop="paymentDate">
        <el-date-picker
          v-model="paymentForm.paymentDate"
          type="date"
          placeholder="请选择支付日期"
          style="width: 100%"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item label="收据号" prop="receiptNumber">
        <el-input
          v-model="paymentForm.receiptNumber"
          placeholder="请输入收据号"
          maxlength="50"
        />
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="paymentForm.remark"
          type="textarea"
          placeholder="请输入备注信息"
          :rows="3"
          maxlength="500"
          show-word-limit
        />
      </el-form-item>
    </el-form>

    <!-- 操作按钮 -->
    <div class="form-actions">
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="primary" @click="handleSubmit" :loading="submitting">
        确认支付
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, type FormInstance, type FormRules } from 'vue'
import { ElMessage } from 'element-plus'
import { Money } from '@element-plus/icons-vue'
import { shopRentApi } from '@/api/shop-rent'
import type { ShopRentRecordVO } from '../types'
import type { PaymentInfo } from '@/api/shop-rent'

// 租金信息接口定义
interface RentInfo {
  id: number
  shopId: number
  shopName: string
  ownerName: string
  rentAmount: number
  dueDate: string
  rentPeriod: string
  rentStartDate: string
  rentEndDate: string
  paymentStatus: number
  paymentStatusName?: string
  createTime?: string
  updateTime?: string
  remark?: string
}

// Props
interface Props {
  rentId: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  success: []
  cancel: []
}>()

// 响应式数据
const formRef = ref<FormInstance>()
const loading = ref(false)
const submitting = ref(false)
const rentInfo = ref<RentInfo>({} as RentInfo)

// 支付表单数据
const paymentForm = reactive<PaymentInfo>({
  paymentAmount: 0,
  paymentMethod: 'CASH',
  paymentDate: '',
  receiptNumber: '',
  remark: '',
  paymentVoucher: ''
})

// 表单验证规则
const formRules: FormRules = {
  paymentMethod: [
    { required: true, message: '请选择支付方式', trigger: 'change' }
  ],
  paymentDate: [
    { required: true, message: '请选择支付日期', trigger: 'change' }
  ],
  receiptNumber: [
    { required: true, message: '请输入收据号', trigger: 'blur' }
  ]
}

// 生命周期
onMounted(() => {
  loadRentInfo()
  // 设置默认支付日期为今天
  paymentForm.paymentDate = new Date().toISOString().split('T')[0]
})

// 方法
const loadRentInfo = async () => {
  loading.value = true
  try {
    const response = await shopRentApi.getRentRecordDetail(props.rentId)
    
    // 根据《Element Plus组件编码规范权威标准声明.md》规范，API响应结构是扁平的
    if (response && response.message === '查询成功' && response.data) {
      const apiData = response.data
      console.log('API返回的原始数据:', apiData)
      
      // 数据字段映射和格式化，遵循《Element Plus组件编码规范权威标准声明.md》规范
      rentInfo.value = {
        id: apiData.id,
        shopId: apiData.shopId,
        shopName: apiData.shopName || '未知店铺',
        ownerName: apiData.ownerName || '未知业主',
        rentAmount: parseFloat(apiData.rentAmount) || 0,
        dueDate: apiData.dueDate || apiData.rentEndDate || '',
        rentPeriod: apiData.rentPeriod || apiData.rentMonth || '',
        rentStartDate: apiData.rentStartDate || apiData.leaseStartDate || '',
        rentEndDate: apiData.rentEndDate || apiData.leaseEndDate || '',
        paymentStatus: parseInt(apiData.paymentStatus) || 0,
        paymentStatusName: getPaymentStatusName(parseInt(apiData.paymentStatus) || 0),
        createTime: apiData.createTime || '',
        updateTime: apiData.updateTime || '',
        remark: apiData.remark || ''
      }
      
      // 设置支付金额
      paymentForm.paymentAmount = parseFloat(apiData.rentAmount) || 0
      
      console.log('处理后的租金信息数据:', rentInfo.value)
    } else {
      const errorMsg = response?.message || '租金记录不存在'
      ElMessage.error(errorMsg)
      console.error('API返回错误:', response)
    }
  } catch (error) {
    ElMessage.error('加载租金信息失败')
    console.error('加载租金信息失败:', error)
  } finally {
    loading.value = false
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    submitting.value = true
    
    // 调用支付API
    const response = await shopRentApi.payRent(props.rentId, paymentForm)
    
    // 根据《Element Plus组件编码规范权威标准声明.md》规范，API响应结构是扁平的
    if (response && response.message === '支付成功') {
      ElMessage.success(response.message || '支付成功')
      emit('success')
    } else {
      ElMessage.error(response?.message || '支付失败')
    }
  } catch (error) {
    if (error !== false) {
      ElMessage.error('支付失败')
      console.error('支付失败:', error)
    }
  } finally {
    submitting.value = false
  }
}

const handleCancel = () => {
  emit('cancel')
}

// 获取支付状态标签类型，遵循《系统状态枚举权威标准声明.md》规范
const getPaymentStatusTagType = (status: number) => {
  const typeMap = {
    0: 'danger',  // 未支付
    1: 'success', // 已支付
    2: 'warning'  // 逾期
  }
  return typeMap[status as keyof typeof typeMap] || 'info'
}

// 获取支付状态名称，遵循《系统状态枚举权威标准声明.md》规范
const getPaymentStatusName = (status: number) => {
  const statusMap = {
    0: '未支付',
    1: '已支付', 
    2: '逾期'
  }
  return statusMap[status as keyof typeof statusMap] || '未知状态'
}

// 安全的金额格式化函数，遵循《Element Plus组件编码规范权威标准声明.md》规范
const formatMoney = (amount: any): string => {
  try {
    if (amount === null || amount === undefined || amount === '') {
      return '0.00'
    }
    
    // 确保是数字类型
    const num = typeof amount === 'number' ? amount : parseFloat(amount)
    
    // 检查是否为有效数字
    if (isNaN(num) || !isFinite(num)) {
      return '0.00'
    }
    
    // 格式化数字，保留两位小数
    return num.toFixed(2)
  } catch (error) {
    console.warn('formatMoney error:', error, 'amount:', amount)
    return '0.00'
  }
}
</script>

<style scoped>
.shop-rent-payment {
  padding: 20px;
}

.rent-info-card {
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 600;
  color: #303133;
}

.payment-form {
  margin-bottom: 20px;
}

.form-actions {
  text-align: center;
}

.form-actions .el-button {
  margin: 0 8px;
  min-width: 100px;
}

.money-text {
  color: #f56c6c;
  font-weight: 600;
  font-size: 18px;
}

.name-text {
  font-weight: 500;
  color: #303133;
}

:deep(.el-form-item__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-descriptions__label) {
  font-weight: 600;
  color: #606266;
}

:deep(.el-descriptions__content) {
  color: #303133;
}
</style>
